{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1E3519VKVwHYaDrg6CbSHBYFBXp9t8We4?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>"
      ],
      "metadata": {
        "id": "yF4P9hUtowqt"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "VW_BhXwLouj8"
      },
      "outputs": [],
      "source": [
        "!pip install -qU google-generativeai"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import google.generativeai as genai\n",
        "import getpass\n",
        "from collections import Counter"
      ],
      "metadata": {
        "id": "e7QS_ul5o7zA"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Get free-tier Google's Gemini API Key here: https://aistudio.google.com/app/apikey"
      ],
      "metadata": {
        "id": "-CRXuVzro-XG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "API_KEY = getpass.getpass(\"Enter your Google API key: \")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "GESjM9iBo_3Y",
        "outputId": "9fe40f10-4406-4ae7-a5e3-01b147675663"
      },
      "execution_count": 3,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Enter your Google API key: ··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "genai.configure(api_key=API_KEY)"
      ],
      "metadata": {
        "id": "kWpv4pT_pDhs"
      },
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class CoT:\n",
        "    def __init__(self):\n",
        "        self.model = genai.GenerativeModel(\"gemini-2.0-flash-exp\")\n",
        "\n",
        "    def zero_shot_cot(self, question):\n",
        "        \"\"\"Zero-Shot CoT: 'Let's think step by step'\"\"\"\n",
        "        print(f\"\\n{'='*60}\")\n",
        "        print(f\"🧠 Zero-Shot CoT\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"Question: {question}\\n\")\n",
        "\n",
        "        prompt = f\"\"\"{question}\n",
        "\n",
        "        Let's think step by step.\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "        print(f\"Reasoning:\\n{response}\\n\")\n",
        "\n",
        "        return response\n",
        "\n",
        "    def few_shot_cot(self, question, examples):\n",
        "        \"\"\"Few-Shot CoT: Provide examples with reasoning\"\"\"\n",
        "        print(f\"\\n{'='*60}\")\n",
        "        print(f\"📚 Few-Shot CoT\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"Question: {question}\\n\")\n",
        "\n",
        "        # Build prompt with examples\n",
        "        examples_text = \"\\n\\n\".join([\n",
        "            f\"Q: {ex['question']}\\nA: {ex['reasoning']}\"\n",
        "            for ex in examples\n",
        "        ])\n",
        "\n",
        "        prompt = f\"\"\"Here are some examples:\n",
        "\n",
        "        {examples_text}\n",
        "\n",
        "        Now solve this:\n",
        "\n",
        "        Q: {question}\n",
        "        A: Let's think step by step.\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "        print(f\"Reasoning:\\n{response}\\n\")\n",
        "\n",
        "        return response\n",
        "\n",
        "    def self_consistency(self, question, num_paths=5):\n",
        "        \"\"\"Self-Consistency: Multiple reasoning paths + majority vote\"\"\"\n",
        "        print(f\"\\n{'='*60}\")\n",
        "        print(f\"🔄 Self-Consistency CoT ({num_paths} paths)\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"Question: {question}\\n\")\n",
        "\n",
        "        answers = []\n",
        "\n",
        "        for i in range(num_paths):\n",
        "            print(f\"Path {i+1}:\")\n",
        "\n",
        "            prompt = f\"\"\"{question}\n",
        "\n",
        "            Let's think step by step.\"\"\"\n",
        "\n",
        "            response = self.model.generate_content(prompt).text\n",
        "\n",
        "            # Extract final answer (last line or number)\n",
        "            lines = response.strip().split(\"\\n\")\n",
        "            final_answer = lines[-1].strip()\n",
        "\n",
        "            # Try to extract just the answer value\n",
        "            import re\n",
        "            numbers = re.findall(r'\\d+\\.?\\d*', final_answer)\n",
        "            if numbers:\n",
        "                final_answer = numbers[-1]\n",
        "\n",
        "            answers.append(final_answer)\n",
        "            print(f\"  Answer: {final_answer}\\n\")\n",
        "\n",
        "        # Majority vote\n",
        "        vote_counts = Counter(answers)\n",
        "        majority_answer = vote_counts.most_common(1)[0][0]\n",
        "\n",
        "        print(f\"{'─'*60}\")\n",
        "        print(f\"📊 Vote Results:\")\n",
        "        for answer, count in vote_counts.items():\n",
        "            print(f\"  {answer}: {count} votes\")\n",
        "        print(f\"\\n🏆 Majority Answer: {majority_answer}\\n\")\n",
        "\n",
        "        return majority_answer\n",
        "\n",
        "    def compare_methods(self, question, examples=None):\n",
        "        \"\"\"Compare all three CoT methods\"\"\"\n",
        "        print(f\"\\n{'='*70}\")\n",
        "        print(f\"🔬 COMPARING CoT METHODS\")\n",
        "        print(f\"{'='*70}\\n\")\n",
        "\n",
        "        # Method 1: Zero-Shot\n",
        "        zero_shot_result = self.zero_shot_cot(question)\n",
        "\n",
        "        # Method 2: Few-Shot (if examples provided)\n",
        "        if examples:\n",
        "            few_shot_result = self.few_shot_cot(question, examples)\n",
        "\n",
        "        # Method 3: Self-Consistency\n",
        "        self_consistency_result = self.self_consistency(question, num_paths=3)\n",
        "\n",
        "        print(f\"{'='*70}\")\n",
        "        print(f\"📋 SUMMARY\")\n",
        "        print(f\"{'='*70}\")\n",
        "        print(f\"Zero-Shot: Check output above\")\n",
        "        if examples:\n",
        "            print(f\"Few-Shot: Check output above\")\n",
        "        print(f\"Self-Consistency: {self_consistency_result}\")\n",
        "        print()"
      ],
      "metadata": {
        "id": "s5G7fkKqpHKB"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Initialize\n",
        "cot = CoT()\n",
        "\n",
        "# Example 1: Math Word Problem\n",
        "print(\"=\"*70)\n",
        "print(\"EXAMPLE 1: Math Word Problem\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "math_question = \"\"\"Roger has 5 tennis balls. He buys 2 more cans of tennis balls.\n",
        "Each can has 3 tennis balls. How many tennis balls does he have now?\"\"\"\n",
        "\n",
        "cot.zero_shot_cot(math_question)\n",
        "\n",
        "\n",
        "# Example 2: Few-Shot CoT with Examples\n",
        "print(\"\\n\" + \"=\"*70)\n",
        "print(\"EXAMPLE 2: Few-Shot CoT with Examples\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "examples = [\n",
        "    {\n",
        "        \"question\": \"John has 3 apples. He buys 2 more. How many does he have?\",\n",
        "        \"reasoning\": \"John starts with 3 apples. He buys 2 more. So 3 + 2 = 5. The answer is 5.\"\n",
        "    },\n",
        "    {\n",
        "        \"question\": \"A box has 4 red balls and 3 blue balls. How many balls total?\",\n",
        "        \"reasoning\": \"Red balls: 4. Blue balls: 3. Total = 4 + 3 = 7. The answer is 7.\"\n",
        "    }\n",
        "]\n",
        "\n",
        "new_question = \"Sara has 8 cookies. She gives 3 to her friend and buys 5 more. How many cookies does Sara have now?\"\n",
        "\n",
        "cot.few_shot_cot(new_question, examples)\n",
        "\n",
        "\n",
        "# Example 3: Self-Consistency\n",
        "print(\"\\n\" + \"=\"*70)\n",
        "print(\"EXAMPLE 3: Self-Consistency CoT\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "tricky_question = \"\"\"A farmer has 17 sheep. All but 9 die. How many sheep are left?\"\"\"\n",
        "\n",
        "cot.self_consistency(tricky_question, num_paths=5)\n",
        "\n",
        "\n",
        "# Example 4: Logical Reasoning\n",
        "print(\"\\n\" + \"=\"*70)\n",
        "print(\"EXAMPLE 4: Logical Reasoning\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "logic_question = \"\"\"All roses are flowers. Some flowers fade quickly.\n",
        "Does this mean some roses fade quickly?\"\"\"\n",
        "\n",
        "cot.zero_shot_cot(logic_question)\n",
        "\n",
        "\n",
        "# Example 5: Commonsense Reasoning\n",
        "print(\"\\n\" + \"=\"*70)\n",
        "print(\"EXAMPLE 5: Commonsense Reasoning\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "commonsense_question = \"\"\"If you drop a glass vase on a concrete floor, what will happen?\"\"\"\n",
        "\n",
        "cot.zero_shot_cot(commonsense_question)\n",
        "\n",
        "\n",
        "# Example 6: Compare All Methods\n",
        "print(\"\\n\" + \"=\"*70)\n",
        "print(\"EXAMPLE 6: Compare All Methods\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "comparison_question = \"\"\"A restaurant has 23 tables. Each table has 4 chairs.\n",
        "If 3 tables are broken and removed, how many chairs are left?\"\"\"\n",
        "\n",
        "comparison_examples = [\n",
        "    {\n",
        "        \"question\": \"A classroom has 6 rows. Each row has 5 desks. How many desks total?\",\n",
        "        \"reasoning\": \"6 rows × 5 desks per row = 30 desks. The answer is 30.\"\n",
        "    }\n",
        "]\n",
        "\n",
        "cot.compare_methods(comparison_question, comparison_examples)\n",
        "\n",
        "\n",
        "# Example 7: Complex Multi-Step Problem\n",
        "print(\"\\n\" + \"=\"*70)\n",
        "print(\"EXAMPLE 7: Complex Multi-Step Reasoning\")\n",
        "print(\"=\"*70)\n",
        "\n",
        "complex_question = \"\"\"A store sells notebooks for $3 each and pens for $2 each.\n",
        "Sarah buys 4 notebooks and 6 pens. She pays with a $50 bill.\n",
        "How much change does she receive?\"\"\"\n",
        "\n",
        "cot.zero_shot_cot(complex_question)\n",
        "\n",
        "\n",
        "print(\"✅ Chain-of-Thought Prompting Complete!\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "Fzw_cxf0pQk0",
        "outputId": "bb16385d-51ef-45f4-e445-54d50cab1aa4"
      },
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "======================================================================\n",
            "EXAMPLE 1: Math Word Problem\n",
            "======================================================================\n",
            "\n",
            "============================================================\n",
            "🧠 Zero-Shot CoT\n",
            "============================================================\n",
            "Question: Roger has 5 tennis balls. He buys 2 more cans of tennis balls. \n",
            "Each can has 3 tennis balls. How many tennis balls does he have now?\n",
            "\n",
            "Reasoning:\n",
            "Here's how to solve the problem step-by-step:\n",
            "\n",
            "1. **Calculate the number of tennis balls in the cans:** Roger buys 2 cans * 3 tennis balls/can = 6 tennis balls.\n",
            "2. **Calculate the total number of tennis balls:** Roger has 5 tennis balls + 6 tennis balls = 11 tennis balls.\n",
            "\n",
            "**Answer:** Roger has 11 tennis balls now.\n",
            "\n",
            "\n",
            "\n",
            "======================================================================\n",
            "EXAMPLE 2: Few-Shot CoT with Examples\n",
            "======================================================================\n",
            "\n",
            "============================================================\n",
            "📚 Few-Shot CoT\n",
            "============================================================\n",
            "Question: Sara has 8 cookies. She gives 3 to her friend and buys 5 more. How many cookies does Sara have now?\n",
            "\n",
            "Reasoning:\n",
            "Sara starts with 8 cookies. She gives 3 away, so she has 8 - 3 = 5 cookies. Then she buys 5 more, so she has 5 + 5 = 10 cookies. The answer is 10.\n",
            "\n",
            "\n",
            "\n",
            "======================================================================\n",
            "EXAMPLE 3: Self-Consistency CoT\n",
            "======================================================================\n",
            "\n",
            "============================================================\n",
            "🔄 Self-Consistency CoT (5 paths)\n",
            "============================================================\n",
            "Question: A farmer has 17 sheep. All but 9 die. How many sheep are left?\n",
            "\n",
            "Path 1:\n",
            "  Answer: 9.\n",
            "\n",
            "Path 2:\n",
            "  Answer: 9\n",
            "\n",
            "Path 3:\n",
            "  Answer: 9.\n",
            "\n",
            "Path 4:\n",
            "  Answer: 9.\n",
            "\n",
            "Path 5:\n",
            "  Answer: 9\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "📊 Vote Results:\n",
            "  9.: 3 votes\n",
            "  9: 2 votes\n",
            "\n",
            "🏆 Majority Answer: 9.\n",
            "\n",
            "\n",
            "======================================================================\n",
            "EXAMPLE 4: Logical Reasoning\n",
            "======================================================================\n",
            "\n",
            "============================================================\n",
            "🧠 Zero-Shot CoT\n",
            "============================================================\n",
            "Question: All roses are flowers. Some flowers fade quickly. \n",
            "Does this mean some roses fade quickly?\n",
            "\n",
            "Reasoning:\n",
            "* **Premise 1:** All roses are flowers. This means the set of roses is entirely contained within the set of flowers.\n",
            "* **Premise 2:** Some flowers fade quickly. This means there's an overlap between the set of flowers and the set of things that fade quickly.\n",
            "\n",
            "Because the set of roses is entirely contained within the set of flowers, and some flowers fade quickly, it's *possible* that the roses are among those flowers that fade quickly. However, it's also *possible* that the roses are among the flowers that *don't* fade quickly.\n",
            "\n",
            "Therefore, we cannot definitively conclude that some roses fade quickly.\n",
            "\n",
            "**Answer:** It is possible, but not necessarily true. We cannot say for certain that some roses fade quickly.\n",
            "\n",
            "\n",
            "\n",
            "======================================================================\n",
            "EXAMPLE 5: Commonsense Reasoning\n",
            "======================================================================\n",
            "\n",
            "============================================================\n",
            "🧠 Zero-Shot CoT\n",
            "============================================================\n",
            "Question: If you drop a glass vase on a concrete floor, what will happen?\n",
            "\n",
            "Reasoning:\n",
            "Okay, let's break this down step by step:\n",
            "\n",
            "1.  **Gravity:** Gravity will pull the vase downwards.\n",
            "\n",
            "2.  **Acceleration:** As the vase falls, it will accelerate, meaning its speed will increase.\n",
            "\n",
            "3.  **Impact:** The vase will collide with the concrete floor.\n",
            "\n",
            "4.  **Force:** At the point of impact, a significant force will be exerted on both the vase and the floor. The force will be determined by the vase's mass, velocity, and the deceleration it experiences upon impact.\n",
            "\n",
            "5.  **Material Properties:**\n",
            "    *   **Glass:** Glass is a brittle material. This means it's strong under compression, but weak under tension and doesn't deform much before breaking.\n",
            "    *   **Concrete:** Concrete is a hard, rigid material.\n",
            "\n",
            "6.  **Stress and Strain:** The impact will create stress within the glass. The stress will be concentrated at the point of contact and propagate outwards.\n",
            "\n",
            "7.  **Fracture:** Because glass is brittle and the impact force is high, the stress will quickly exceed the glass's tensile strength. This will cause the glass to fracture, creating cracks that spread rapidly.\n",
            "\n",
            "8.  **Shattering:** The vase will likely shatter into many pieces. The number and size of the pieces will depend on the height of the drop, the shape and thickness of the glass, and the precise point of impact. Some pieces may be small shards, while others may be larger fragments.\n",
            "\n",
            "**Conclusion:**\n",
            "\n",
            "The glass vase will shatter into many pieces upon impact with the concrete floor. It's a near certainty.\n",
            "\n",
            "\n",
            "\n",
            "======================================================================\n",
            "EXAMPLE 6: Compare All Methods\n",
            "======================================================================\n",
            "\n",
            "======================================================================\n",
            "🔬 COMPARING CoT METHODS\n",
            "======================================================================\n",
            "\n",
            "\n",
            "============================================================\n",
            "🧠 Zero-Shot CoT\n",
            "============================================================\n",
            "Question: A restaurant has 23 tables. Each table has 4 chairs. \n",
            "If 3 tables are broken and removed, how many chairs are left?\n",
            "\n",
            "Reasoning:\n",
            "1. **Start with the initial number of tables:** The restaurant begins with 23 tables.\n",
            "2. **Calculate the number of tables after removal:** 3 tables are removed, so there are 23 - 3 = 20 tables left.\n",
            "3. **Calculate the total number of chairs remaining:** Each of the remaining 20 tables has 4 chairs, so there are 20 * 4 = 80 chairs left.\n",
            "\n",
            "**Answer:** There are 80 chairs left.\n",
            "\n",
            "\n",
            "\n",
            "============================================================\n",
            "📚 Few-Shot CoT\n",
            "============================================================\n",
            "Question: A restaurant has 23 tables. Each table has 4 chairs. \n",
            "If 3 tables are broken and removed, how many chairs are left?\n",
            "\n",
            "Reasoning:\n",
            "Here's how we can solve the problem step-by-step:\n",
            "\n",
            "A: \n",
            "1. **Calculate the number of tables remaining**: 23 tables - 3 tables = 20 tables\n",
            "2. **Calculate the total number of chairs on the remaining tables**: 20 tables × 4 chairs per table = 80 chairs\n",
            "The answer is 80.\n",
            "\n",
            "\n",
            "\n",
            "============================================================\n",
            "🔄 Self-Consistency CoT (3 paths)\n",
            "============================================================\n",
            "Question: A restaurant has 23 tables. Each table has 4 chairs. \n",
            "If 3 tables are broken and removed, how many chairs are left?\n",
            "\n",
            "Path 1:\n",
            "  Answer: 80\n",
            "\n",
            "Path 2:\n",
            "  Answer: 80\n",
            "\n",
            "Path 3:\n",
            "  Answer: 80\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "📊 Vote Results:\n",
            "  80: 3 votes\n",
            "\n",
            "🏆 Majority Answer: 80\n",
            "\n",
            "======================================================================\n",
            "📋 SUMMARY\n",
            "======================================================================\n",
            "Zero-Shot: Check output above\n",
            "Few-Shot: Check output above\n",
            "Self-Consistency: 80\n",
            "\n",
            "\n",
            "======================================================================\n",
            "EXAMPLE 7: Complex Multi-Step Reasoning\n",
            "======================================================================\n",
            "\n",
            "============================================================\n",
            "🧠 Zero-Shot CoT\n",
            "============================================================\n",
            "Question: A store sells notebooks for $3 each and pens for $2 each. \n",
            "Sarah buys 4 notebooks and 6 pens. She pays with a $50 bill. \n",
            "How much change does she receive?\n",
            "\n",
            "Reasoning:\n",
            "1. **Calculate the cost of the notebooks:** 4 notebooks * $3/notebook = $12\n",
            "2. **Calculate the cost of the pens:** 6 pens * $2/pen = $12\n",
            "3. **Calculate the total cost:** $12 (notebooks) + $12 (pens) = $24\n",
            "4. **Calculate the change:** $50 - $24 = $26\n",
            "\n",
            "**Answer:** Sarah receives $26 in change.\n",
            "\n",
            "\n",
            "✅ Chain-of-Thought Prompting Complete!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "5AW4nF5epXxy"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}